# -*-coding:utf-8 -*-
from django.db import models
from easy_thumbnails.fields import ThumbnailerImageField
from easy_thumbnails.files import get_thumbnailer
from django.core import validators
from xpinyin import Pinyin
from core.util import create_qrcode
import os
import uuid
from django.conf import settings
from django.contrib.staticfiles.finders import default_storage
from django.core.files.base import ContentFile
from mptt.models import MPTTModel, TreeForeignKey
from mptt.managers import TreeManager
from django.db import connections
from urllib.parse import urlparse
from django.db.models.signals import m2m_changed, post_save
from django.dispatch import receiver
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import json
NOTIFY_BROKER = getattr(settings, 'NOTIFY_BROKER', None)


class DepartmentManager(TreeManager):
    def children_ids(self, pid):
        if not pid:
            return []
        cursor = connections['default'].cursor()
        sql = 'WITH RECURSIVE T_D AS(\
        SELECT id,parent_id FROM org_department where id=%s UNION \
        SELECT t.id,t.parent_id FROM org_department t  inner join T_D ON t.parent_id = T_D.id\
        ) select id from T_D;'
        cursor.execute(sql, [pid])
        return [row[0] for row in cursor.fetchall()]

    def parents_ids(self, cid):
        if not cid:
            return []
        cursor = connections['default'].cursor()
        sql = 'WITH RECURSIVE T_D AS(\
        SELECT id,parent_id FROM org_department where id=%s UNION \
        SELECT t.id,t.parent_id FROM org_department t  inner join T_D ON t.id = T_D.parent_id\
        ) select id from T_D;'
        cursor.execute(sql, [cid])
        return [row[0] for row in cursor.fetchall()]

class Department(MPTTModel):
    objects = DepartmentManager()
    createdat = models.DateTimeField(u'创建时间', auto_now_add=True, help_text=u'录入本条数据记录的时间，由系统自动生成。')
    spinyin = models.CharField(u'简拼码', max_length=25, null=True, editable=False)
    qrcode = models.ImageField(u'二维码', max_length=200, upload_to='department/qrcode/', blank=True, null=True,)
    pic = models.ImageField(u'照片', upload_to='department/', null=True, blank=True,  help_text=u'部门形象照片')
    parent = TreeForeignKey('self', verbose_name=u'上级', on_delete=models.CASCADE, null=True, blank=True, related_name='sub_departments')
    name = models.CharField(u'名称', max_length=150, help_text=u'*必须填写机构的名称。')
    description = models.TextField(u'简介', blank=True, null=True)

    logo = models.ImageField(u'LOGO', max_length=200, upload_to='department/logo/', blank=True, null=True)
    address = models.CharField(u'地址', max_length=255, blank=True, null=True)
    tel = models.CharField(u'联系电话', max_length=255, blank=True, null=True)
    tax = models.CharField(u'传真', max_length=255, blank=True, null=True)
    qr_weixin = models.ImageField(u'企业公众号二维码', max_length=200, upload_to='department/weixin/', blank=True, null=True,)
    email = models.EmailField(u'邮件地址', blank=True, null=True)
    
    # 全局设备控制
    bg_image = models.ImageField(u'展板背景', max_length=200, upload_to='department/boardbox/photo/',  blank=True, null=True, help_text=u'用于显示在展板界面的背景图片，不设置则为纯色背景。')
    welcome = models.CharField(u'欢迎词', max_length=255, null=True, blank=True)

    major_id = models.CharField(u'主平台ID', unique=True, null=True, blank=True, max_length=50, help_text=u'用于与主平台部门数据同步。', editable=False)
    memo = models.CharField(u'备注', max_length=255, blank=True, null=True)

    def get_member_count(self):
        return self.person_set.count()

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name

    def create_qr_code(self):
        obj_id = u'%s.%s.%s' % (self._meta.app_label, self.__class__.__name__, self.id)
        output = create_qrcode(obj_id)
        filename = os.path.join(self._meta.get_field('qrcode').upload_to, '%s.png' % str(uuid.uuid4()))
        path = default_storage.save(filename, ContentFile(output.getvalue()))
        self.qrcode = path

    def create_spinyin(self):
        if not self.name or self.name == '':
            return
        py = Pinyin()
        self.spinyin = py.get_initials(self.name, u'')[:20]

    def clean(self):
        self.create_spinyin()
        if not self.qrcode or self.qrcode is None:
            self.create_qr_code()

    class Meta:
        ordering = ['-parent_id']
        verbose_name = verbose_name_plural = u"部门"

    def save(self, *args, **kwargs):
        super(Department, self).save(*args, **kwargs)


class Person(models.Model):
    GENDER_TYPE = (('M', u"男"), ('F', u"女"),)
    major_id = models.CharField(u'主平台ID', unique=True, null=True, blank=True, max_length=50, help_text=u'用于与主平台部门数据同步。', editable=False)
    pic = models.ImageField(u'照片', upload_to='person/photo/', null=True, blank=True,  help_text=u'2寸照片')
    qrcode = models.ImageField(u'二维码', max_length=200, upload_to='person/qrcode/',  blank=True, null=True, editable=False)
    createdat = models.DateTimeField(u'登记日期', auto_now_add=True, help_text=u'系统自动生成，当前登记的时间')
    name = models.CharField(u'姓名', max_length=25)
    spinyin = models.CharField(u'简拼码', max_length=25,  null=True, blank=True,)
    gender = models.CharField(u'性别', choices=GENDER_TYPE, max_length=1, default='M')
    job = models.CharField(u'职务', max_length=50, blank=True, null=True)
    mobile = models.CharField(u'联系电话', blank=True, null=True, max_length=50, validators=[validators.RegexValidator(
        '^\d{3}-\d{8}|\d{4}-\d{7}|1\d{10}$', u'请输入一个有效的电话号码例如：\'13012345678\',\'028-12345678\'或\'0816-1234567\'')], help_text=u'输入手机号码或固定电话号码，电话号码格式：\'13012345678\',\'028-12345678\'或\'0816-1234567\'')
    department = models.ForeignKey(Department, verbose_name='所属部门', on_delete=models.CASCADE)
    is_leader = models.BooleanField(u'是否领导', default=False)
    description = models.TextField(u'人员介绍', blank=True)
    user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=u'认证账号', blank=True, null=True, on_delete=models.CASCADE)
    def get_thumbnai100x100(self):
        try:
            options = {'size': (100, 100), 'crop': True}
            return get_thumbnailer(self.pic).get_thumbnail(options).url
        except:
            return None
    thumbnai100x100 = property(get_thumbnai100x100)

    def get_department_name(self):
        return u"%s" % self.department

    def create_qr_code(self):
        obj_id = u'%s.%s.%s' % (self._meta.app_label, self.__class__.__name__, self.id)
        output = create_qrcode(obj_id)
        filename = os.path.join(self._meta.get_field('qrcode').upload_to, '%s.png' % str(uuid.uuid4()))
        path = default_storage.save(filename, ContentFile(output.getvalue()))
        self.qrcode = path

    def create_spinyin(self):
        if not self.name or self.name == '':
            return
        py = Pinyin()
        self.spinyin = py.get_initials(self.name, u'')[:20]

    def clean(self):
        self.create_spinyin()
        if not self.qrcode:
            self.create_qr_code()

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name

    class Meta:
        # permissions = (("can_audit_personnel", u"允许审核"),)
        verbose_name_plural = verbose_name = u'人员'

    def save(self, *args, **kwargs):
        super(Person, self).save(*args, **kwargs)


@receiver(post_save, sender=Department)
def auto_push_change_info(sender, instance, **kwargs):
    p = urlparse(NOTIFY_BROKER)
    host, port = p.netloc.split(":")
    topic = "edboard/content/%s" % instance.__class__.__name__.lower()
    # topic = "mr7b/ind/edboard/info/053096912362
    # msg = ''
    publish.single(topic, instance.id, hostname=host, port=int(port))
